import axios from 'axios'
import store from '@/store'
import dox from './do'
import config from './config'
import tips from './tips.js'

//创建 axios 实例
const http = axios.create({
    baseURL: config.BASE_API, //api的base_url
    timeout: 10000, //请求超时时间
})

//request 拦截器
http.interceptors.request.use(
    config => {
        // 自定义的config 配置 PS:http必须有data参数否则报错，可优化处理
        // let token = store.getters['user/getInfo'].token;
        let token = ''
        config.url = dox.doUrlAddParam(config.url, 'token=' + token);
        config.headers['loginFrom'] = 'app';
        // config.headers['loginusertoken'] = token;
        // if (Object.prototype.toString.call(config.data) != '[object FormData]') {//如果data对象已经是FormData就不需要再转换，否则转换
        //     config.data = qs.stringify(config.data);
        // }
        store.commit('loading/clearProgress')//重置进度
        if (hasShowLoading(config.url)) {
            store.dispatch('loading/setLoading', true);//loading +1
            if (hasShowProgress(config.url)) {//进度
                config.onUploadProgress = (progressEvent) => {
                    let num = (progressEvent.loaded / progressEvent.total * 100 | 0)
                    store.commit('loading/setProgress', num)
                }
            }
        }
        return config;
    },
    error => {
        //错误处理
        // loading 清 0 
        setTimeout(function () {
            store.dispatch('loading/setLoading', 0)
        }, 300)
        console.log(error);
        Promise.reject(error);
    }
)

//response 拦截器
http.interceptors.response.use(
    response => {
        const res = response.data;
        if (hasShowLoading(response.config.url)) {
            store.dispatch('loading/setLoading', false);//loading - 1
        }
        return res;
    },
    error => {
        console.error('请求报错了')
        //请求无响应
        if(error.isAxiosError && dox.doIsNull(error.response)){
            store.dispatch('loading/setLoading', 0);
            let msg = dox.doIsNull(error.message) ? '接口无响应' : error.message
            tips.fail(msg);
            return error
        }

        //请求响应，但报错
        if (hasShowLoading(error.response.config.url)) {
            store.dispatch('loading/setLoading', false);//loading - 1
        }
        if (error.response.status == '404' || error.response.status == '400') {
            tips.fail(error.response.status);
        }
        else {
            tips.fail(error.response.data.msg);
        }
        return Promise.resolve(error.response.data);
    }
)

function hasShowLoading(url) {
    return url.indexOf('showLoading=true') > -1;
}

function hasShowProgress(url) {
    return url.indexOf('showProgress=true') > -1;
}

export default http;